
function triggerClickVisitor(cid, start) {
	var id = start + "_CRM_" + cid + "_LI";
	$("#" + id).addClass("active").siblings().removeClass("active");
	clickVisitor(cid, start);
}
function clickVisitor(cid, start, liId) {
	var lid = null;//
	if(start == "L" || start == "M") {
		cid = liId.substring(2, liId.indexOf("_LW"));
		//截取lid
		lid = liId.substring(liId.indexOf("_LW") + 1, liId.length - 3);
	}
	//最后一次点击的访客类型：聊天中、排队、等待协助、历史
	lastClickVisitorType = start;
	if (start == "T") {
		currentVisitorId = cid;
	} else if (start == "Q") {
		currentQueueVisitorId = cid;
	} else if (start == "W") {
		currentWaitingVisitorId = cid;
	}
	delete pgData[cid];
	$("#msgHolder").html("");
	getLog(cid);
	var visitor = null;
	if (start == "Q") {
		visitor = theQueue[cid];
	} else if (start == "T") {
		visitor = talkingVisitor[cid];
		resetVisitorUnreadCount(cid);
		if (visitor.visitorStatus == MEMBER_STATUS.OFFLINE) {
			showTip(AGENT_TEXT.OFFLINE_TIP);
		} else {
			if (visitor.visitorStatus == MEMBER_STATUS.END) {
				showTip(AGENT_TEXT.END_TIP);
			}
		}
	} else if (start == "H") {
		visitor = historyVisitor[cid];
	} else if (start == "W") {
		visitor = waitingVisitor[cid];
	}
	getCrm(cid);
	getCrmHistory(cid);
	getCrmTrace(cid);
	getCrmSession(cid);
	showButtons(visitor, start, lid, liId);
}
function resetVisitorUnreadCount(cid) {
	talkingVisitor[cid].unreadCount = 0;
	talkingVisitor[cid].isNew = false;
	showTalkingUnreadCount(cid);
	showMyVisitorUnreadCount();
	showSessionUnreadCount();
}
function selectTheFirst() {
	for (var one in talkingVisitor) {
		triggerClickVisitor(talkingVisitor[one].object.crm.id, "T");
		break;
	}
}
function handlerNotify(message) {
	if (message.notify == MESSAGE_NOTIFY.AGENT_CONFIG) {
		if (message.object.status == "OFFLINE") {
			$(".b_" + message.sender).removeClass("web-online");
			$(".b_" + message.sender).addClass("web-offline");
			$(".c_" + message.sender).html("--");
		} else {
			$(".b_" + message.sender).removeClass("web-offline");
			$(".b_" + message.sender).addClass("web-online");
			$(".c_" + message.sender).html(message.object.currentChat + "/" + message.object.maxChat + "/" + AGENT_TEXT[message.object.status]);
			//如果是自己，则需要变更这个状态值
			if(message.sender == agentSelfInfo.username) {
				$("#serviceStatus").val(message.object.status);
				if(message.object.status == SERVICE_STATUS.ONLINE) {
					$("#currentServiceStatus").removeClass("offline-icons");
				} else {
					$("#currentServiceStatus").addClass("offline-icons");
				}
			}
		}
	} else if (message.notify == MESSAGE_NOTIFY.QUEUE_ADD_ED) {
		var crm = message.object.crm;
		if (!vl(theQueue[crm.id])) {
			theQueue[crm.id] = message;
			theQueue[crm.id].visitorStatus = MEMBER_STATUS.QUEUE;
		}
		showQueueVisitor(message);
		$("#queueingCount").html("[" + Object.getOwnPropertyNames(theQueue).length + "]");
	} else if (message.notify == MESSAGE_NOTIFY.QUEUE_RECEIVE_ED) {
		var crm = message.object;
		delete theQueue[crm.id];
		removeQueueVisitor(crm);
		$("#queueingCount").html("[" + Object.getOwnPropertyNames(theQueue).length + "]");
		if(currentQueueVisitorId == crm.id) {
			currentQueueVisitorId = "";
		}
	} else if (message.notify == MESSAGE_NOTIFY.AG_INVITE_AGENT || message.notify == MESSAGE_NOTIFY.AG_TRANSFER2_AGENT) {//收到其他坐席的邀请进入
		var crm = message.object.crm;
		var agent = message.object.agent;
		showWaitingVisitor(message);
		//存储数据
		waitingVisitor[crm.id] = message;
	} else if (message.notify == MESSAGE_NOTIFY.AG_INVITE_AGENT_REJECT_ED) {//收到系统通知:邀请的坐席拒接了会话
		var crm = message.object.crm;
		var agent = message.object.agent;
		showLayer("[" + crm.name + "]" + AGENT_TEXT.INVITING_AGENT + "[" + agent.username + "]" + AGENT_TEXT.REJECT2);
		showChatMessge(message);
	} else if (message.notify == MESSAGE_NOTIFY.AG_INVITE_AGENT_ACCEPT_ED) {//收到系统通知:邀请的坐席接受了会话
		var crm = message.object.crm;
		var agent = message.object.agent;
		showLayer("[" + crm.name + "]" + AGENT_TEXT.INVITING_AGENT + "[" + agent.username + "]" + AGENT_TEXT.ACCEPT2);
		showChatMessge(message);
		//显示为群聊
		showLiAsGroup("T_" + crm.id + "_LI");
	} else if (message.notify == MESSAGE_NOTIFY.AG_INVITE_AGENT_CANCEL_ED) {//TODO
		var crm = message.object;
		delete waitingVisitor[crm.id];
		removeWaitingVisitor(crm);
		if(currentWaitingVisitorId == crm.id) {
			currentWaitingVisitorId = "";
		}
	} else if (message.notify == MESSAGE_NOTIFY.INVITE) {
		var crm = message.object.crm;
		if (!vl(talkingVisitor[crm.id])) {
			talkingVisitor[crm.id] = message;
			talkingVisitor[crm.id].isNew = true;
		}
		showTalkingVisitor(message);
		$("#talkingCount").html("[" + Object.getOwnPropertyNames(talkingVisitor).length + "]");
		flashTitle();
		showNotify(TEXT.AGENT_HAVE_NEW_MESSAGE);
		//仅有一个用户的时候就直接展示
		if (Object.getOwnPropertyNames(talkingVisitor).length == 1) {
			showTalkingDiv();
			//selectTheFirst();
		}
		showTalkingUnreadCount(crm.id);
		showMyVisitorUnreadCount();
		showSessionUnreadCount();
	} else if (message.notify == MESSAGE_NOTIFY.MEMBER_STATUS) {//̬{sessionId:xxx,visitorId:yyy,object:{member:object1,memberType:v,status:online}}
		if (!vl(talkingVisitor[message.cid])) {
			showLayer(TEXT.VISITOR_ERROR);
		} else {
			if (message.object.memberType == "v") {
				talkingVisitor[message.cid].visitorStatus = message.object.status;
			} else {//另外一个坐席进入
				showLayer("[" + message.object.memberNickname + "]" + AGENT_TEXT.AGENT_ENTER);
			}
			changeTheVisitorStatus(talkingVisitor[message.cid]);
		}
	} else if (message.notify == MESSAGE_NOTIFY.AG_END_SESSION_ED || message.notify == MESSAGE_NOTIFY.AG_TRANSFER2_SUCCESS) {
		if (!vl(talkingVisitor[message.cid])) {
			showLayer(TEXT.VISITOR_ERROR);
		} else {
			//迁入历史变量
			historyVisitor[message.cid] = talkingVisitor[message.cid];
			historyVisitor[message.cid].visitorStatus = MEMBER_STATUS.HISTORY;
			removeTalkingVisitor(talkingVisitor[message.cid].object.crm);
			showHistoryVisitor(historyVisitor[message.cid]);
			//删除聊天中的变量
			delete talkingVisitor[message.cid];
			currentVisitorId = null;
			
			$("#talkingCount").html("[" + Object.getOwnPropertyNames(talkingVisitor).length + "]");
			$("#historyCount").html("[" + Object.getOwnPropertyNames(historyVisitor).length + "]");
			showMyVisitorUnreadCount();
			showSessionUnreadCount();
			showLayer(AGENT_TEXT[message.notify]);
			if (Object.getOwnPropertyNames(talkingVisitor).length > 0) {
				selectTheFirst();
			} else {
				showButtons("", "");
			}							
		}
	} else {
		showLayer(AGENT_TEXT[message.notify]);
	}
}
function initEvents() {
	$(function () {
		$("#talkingUL,#historyUL,#queueingUL,#handledUL,#noHandledUL,#waitingUL").on("click", "li", function (e) {
			$(this).addClass("active").siblings().removeClass("active");
			var start = this.id.substring(0, 1);
			var cid = this.id.substring(2, this.id.length - 3);
			clickVisitor(cid, start, this.id);
		});
		$("#cutBtn").on("click", function (e) {
			noticeCut();
		});
		$("#audioBtn").on("click", function (e) {
			recordAudio();
		});
		$("#cancelRecord").on("click", function (e) {
			cancelRecordAudio();
		});
		$("#sendRecord").on("click", function (e) {
			sendRecordAudio();
		});
		$("#stopRecord").on("click", function (e) {
			cancelRecordAudio(true);
		});
		$("#satisfyBtn").on("click", function (e) {
			sendSatisfy();
		});
		$("#worderBtn").on("click", function (e) {
			createWorder();
		});
		$("#gchatBtn").on("click", function (e) {
			toInviteAgents('gchat');
		});
		$("#transferBtn").on("click", function (e) {
			toInviteAgents('transfer');
		});
		$("#cancelInvite").on("click", function (e) {
			cancelInvite();
		});
		$("#mapBtn").on("click", function (e) {
			toShowMap();
		});
		
		$('#emojiBtn').bind({
			click : function(event) {
				isSelectEmotion = true;
				if (!$('#wechatEmotion').is(':visible')) {
					$(this).wechatEmotion('#layimVisitorEditor', keditor);
					if (event.stopPropagation) {
						event.stopPropagation();
					} else if (window.event) {
						window.event.cancleBubble = true;
					}
				}
			}
		});	
		$('#province').live('change', function() {
			loadCitryOfProvince($('#province').val());
		});	
	});
}

function noticeCut() {
	if(!currentVisitorId) {
		showLayer(AGENT_TEXT.DO_SEND_ONLY_TALKING);
		return false;
	}
	showLayer(TEXT.CUT_TIP, 6000);
}

function sendSatisfy() {
	if(!currentVisitorId) {
		showLayer(AGENT_TEXT.DO_SEND_ONLY_TALKING);
		return false;
	}
	layer.confirm(AGENT_TEXT.CONFIRM_SATISFY, {title:TEXT.CONFIRM_TITLE, shadeClose:true, btn:[TEXT.CONFIRM, TEXT.CANCEL]}, function () {
		var data = {event:MESSAGE_EVENT.AG_SEND_SATISFY, cid:currentVisitorId};
		send(data, function (resp) {
			layer.closeAll();
			if (resp.code == 0) {
				showLayer(TEXT.DO_SUCCESS);
			} else {
				showLayer(AGENT_TEXT.SATISFY_ERROR);
			}
			get();
		});
	});
}
function doSend(sendContent, value2, multiType0) {
	if (lastClickVisitorType == "T" && talkingVisitor[currentVisitorId] && talkingVisitor[currentVisitorId].visitorStatus != MEMBER_STATUS.END) {
		var data = {event:MESSAGE_EVENT.CHAT, time:TEXT.SENDING, value:sendContent, cid:currentVisitorId, senderRole:SENDER_ROLE.AGENT};
		if (multiType0) {
			data.multiType = multiType0;
		} else {
			data.multiType = MULIT_TYPE.TEXT;
		}
		send(data, function (result) {
			showChatMessge(data);
			toBottom();
			var v = $("#Time" + result.id);
			if (v) {
				if (result.code == 0) {
					v.html(result.time);
				} else {
					v.html(result.time + TEXT.SEND_FAIL);
				}
			}
		});
		resetVisitorUnreadCount(currentVisitorId);
	} else {
		if (lastClickVisitorType == "Q") {
			showLayer(AGENT_TEXT.PLEASE_RECEIVE_QUEUE);
		} else {
			showLayer(AGENT_TEXT.DO_SEND_ONLY_TALKING);
		}
	}
}
function uploadFile() {
	if(!currentVisitorId) {
		showLayer(AGENT_TEXT.DO_SEND_ONLY_TALKING);
		return false;
	}
	
	if ($("#sendFile").val() == "") {
		return;
	}
	if (lastClickVisitorType == "T" && talkingVisitor[currentVisitorId] && talkingVisitor[currentVisitorId].visitorStatus != MEMBER_STATUS.END) {
		var params = {bizType:"CHAT", uploadUrl:UPLOAD_URL};
		MyUpload.uploadFile(params, $("#sendFileForm"), function (resp) {
			if (resp.code == 0) {
				doSend(JSON.stringify(resp), "", MULIT_TYPE.FILE);
			} else {
				showLayer(resp.msg);
			}
			$("#sendFile").val("");
			$("#file").val("");
		});
	} else {
		if (lastClickVisitorType == "Q") {
			showLayer(AGENT_TEXT.PLEASE_RECEIVE_QUEUE);
		} else {
			showLayer(AGENT_TEXT.DO_SEND_ONLY_TALKING);
		}
	}
}

//创建工单
function createWorder() {
	if(!currentVisitorId) {
		showLayer(AGENT_TEXT.DO_SEND_ONLY_TALKING);
		return false;
	}
	var cid = currentVisitorId;
	var sid = talkingVisitor[currentVisitorId].object.session.id;
	layer.open({
		type : 2,
		closeBtn : 1,
		title : "创建工单",
		content : "../biz/TWorderDpAct.do?method=add&cid=" + cid + "&sid="+sid,
		move : false,
		maxmin : true,
		area : [ '80%', '90%' ],
		shadeClose : true,
		cancel: function(){ 
		    layer.closeAll();
		}
	});
}
